

(function($){
	
	//jQuery object extend methods
	$.fn.extend({
		//open the modal with some default values
		"openDialog":function(options){
			options = $.extend({
				width : "200px",
				height : "300px",
				scroll : true,
				hasYesBtn : true,
				hasNoBtn : true,
				confirmBtnHtml : "确定",
				cancelBtnHtml : "取消",
				nobtClose:true,//点击取消是否自动关闭
				yesBtnCss : "btn btn-primary",
				noBtnCss : "btn btn-default",
				isDragable : false,
				dom : false,
				shade : true,
				async : true
			},options || {});
			
			options.id =  $(this).attr("id");
			var id = options.id;
			initBaseTemplate(id);
			initDatas(options);
			initUI(options);
			initEvent(options);
			
			$("#"+id).modal({
				show:true,
				backdrop:"static"
			});
			alterInitPropertiesSet(options);
		}
	});
	
	//create the modal
	
	//modal constructor
	function CfModal(id){
		this.id = id;
	};
	
	CfModal.prototype = {
		
		constructor : CfModal,
		close : function () {
			$("#" + this.id).modal('hide');
			$("#" + this.id).empty();

		},
		remove : function () {},
		rebuildHeader : function (html) {
			$("#" + this.id + " .modal-header").html(html);
		},
		rebuildFooter : function (html) {
			$("#" + this.id + " .modal-footer").html(html);
		}
	};
	
	//edit title
	CfModal.prototype.title = function (newTitle) {};
	//return confirmBtn(jQuery object)
	CfModal.prototype.confirmBtn = function () {};
	//return cancelBtn(jQuery object)
	CfModal.prototype.cancelBtn = function () {};
	
	CfModal.prototype.confirmBtn.text = function (newText) {};
	CfModal.prototype.cancelBtn.text = function (newText) {};
	
	//support a new HTML to footer
	CfModal.prototype.reBuildFooter = function (html) {};
	
	
	var basicDialog = "<div class='modal-dialog'>" +
  	"<div class='modal-content'>" +
  		"<div class='modal-header'>" +
  				"<button type='button' class='close'>" +
  					"<span aria-hidden='true'>×</span>" +
  					"<span class='sr-only'>close</span>" +
  				"</button>" +
  				"<h4 class='modal-title'></h4>" +
  			"</div>" + 
  		 "<div class='modal-body'>" +
  		 
  		 "</div>" +
  		 "<div class='modal-footer'>" +
	  		 "<button type='button' flag='cancelbtn' class='btn btn-default' >取消</button>" +
	  		 "<button type='button' flag='confirmbtn' class='btn btn-primary'>确定</button>" +
  		 "</div>" + 
	  	"</div>" +
 	"</div>";
	
	//initial the basic modal template
	function initBaseTemplate(id) {
		
		$("#"+id).addClass("modal fade in").attr("role","dialog").attr("style","display:block;").attr("tabindex","-1").attr("aria-labelledby","cf-"+id);
		$("#"+id).append(basicDialog);
	};
	

	
	//initial data
	function initDatas(options) {
		
		if (options.async)
			$.beforeLoadingHandler();
		var id = options.id;
		var dom = options.dom;
		var body = $("#"+id).find(".modal-body");
		if (dom && options.html) {
			body.append(options.html);
			if (options.async)
				$.afterLoadingHandler();
		}else {
			if (!options.url){
				//give some alert
				return
			}
			try {
				//AJAX get data
				$.emsAjax({
					cache:false,
					async:options.async,
					type:"POST",
					url:options.url,
					data:options.data,
					success:function(response) {
						body.append(response ? response : "<p color='red'>获取数据失败<p>");
						if (options.async)
							$.afterLoadingHandler();
					}
				});
			}catch (e) {
				
			}
		}
	}
	
	//initial the elements event
	function initEvent(options) {
		
		var modalDiv = $("#"+options.id);
		var dialog = modalDiv.find(".modal-dialog");
		
		modalDiv.on('hidden.bs.modal', function (e) {
			modalDiv.empty();
		});
		
		//isDragable
		if (options.isDragable) {
			dialog.on("mouseup",function(e){
				dialog.unbind("mousemove");
			}).on("mouseleave",function(){
				dialog.unbind("mousemove");
			}).on("mousedown",function(e){
				
				var preXpos = e.pageX;
				var preYpos = e.pageY;
				var offset = dialog.offset();
				var right = $(window).width() - (offset.left + $(this).width() + 20);
				var bottom = $(window).height() - (offset.top + $(this).height());
				dialog.on("mousemove",function(e){
					var left = e.pageX - preXpos;
					var top = e.pageY - preYpos;
					if (Math.abs(left) < offset.left && Math.abs(top) < offset.top && Math.abs(left) < right && Math.abs(top) < bottom) {
						dialog.css({left:left,top:top});
					} 
				});
			});
		}
		
		//confirm and cancel button event
		modalDiv.find(".modal-footer button[flag=confirmbtn]").on("click",function(e){
			
			if (!options.yesFn) {
				modalDiv.modal("hide");
			}else{
				var result = options.yesFn();
				if (result) {
					modalDiv.modal("hide");
				}
			}
		});
		modalDiv.find(".modal-footer button[flag=cancelbtn]").on("click",function(e){
			//取消按钮不自动关闭
			if (!options.cancelFn)
				modalDiv.modal("hide");
			else{
				var result = options.cancelFn();
				if (result || options.nobtClose) {
					modalDiv.modal("hide");
				}
			}
		});
		
		modalDiv.find(".modal-header>.close").on("click",function(e) {
			//取消按钮不自动关闭
			if (options.closeBtnFn)
				options.closeBtnFn();
			modalDiv.modal("hide");
		});
	}
	
	//initial the UI
	function initUI(options) {
		
		var id = options.id;
		var header = $("#"+id).find(".modal-header");
		var footer = $("#"+id).find(".modal-footer");
		var body = $("#"+id).find(".modal-body");
		var dialog = $("#"+id).find(".modal-dialog");
		var content = $("#"+id).find(".modal-content");
		//title
		$("#"+id).find("h4.modal-title").html(options.title);
		//footer
		footer.find("button:eq(0)")
			.text(options.cancelBtnHtml).end()
			.find("button:eq(1)").text(options.confirmBtnHtml);
		
		//width
		dialog.css({
			"width" : options.width
		});
		
		
		var headerHeight = header.height() + 2 * parseInt(header.css("padding-bottom"));
		var footerHeight = footer.height() + 2 * parseInt(footer.css("padding-bottom"));
		var height = parseInt(options.height) - (headerHeight + footerHeight);
		//height,actually the body height
		body.css({
			"height" : options.height
		});
		//default is scroll
		if (scroll) {
			var maxHeight = height;
			body.css({
				"max-height" :maxHeight,
				"overflow" : "auto",
			});
		}
		
		
		//initial position
		if (options.xpos || options.ypos) {
			var marginLeft = parseInt(dialog.css("margin-left"));
			var marginTop = parseInt(dialog.css("margin-top"));
			var right = marginLeft - parseInt(options.xpos ? options.xpos : marginLeft);
			var bottom = marginTop - parseInt(options.ypos ? options.ypos : marginTop);
			content.css({
				"bottom" : bottom,
				"right" : right
			});
		};
		
		//initial button
		options.hasYesBtn ? footer.find("button[flag=confirmbtn]").addClass(options.yesBtnCss) : footer.find("button[flag=confirmbtn]").remove();
		options.hasNoBtn ? footer.find("button[flag=cancelbtn]").addClass(options.noBtnCss) : footer.find("button[flag=cancelbtn]").remove();
		
		if (!options.hasYesBtn && !options.hasNoBtn) 
			footer.find(":button[flag]").remove();
	};
	
	//do some thing to the modal after the initial 
	function alterInitPropertiesSet(options) {
		
		var id = options.id;
		var modalBackdrops = $("#"+id).nextAll("div[class*=in]");
		var currentDrop = $(modalBackdrops[modalBackdrops ? 0 : modalBackdrops.length - 1]);
		if (!options.shade) {
			currentDrop.removeClass("in");
		}
		
		if (options.shade && options.opacity) {
			currentDrop.css("opacity",options.opacity);
		}
	}
	
	// alert modal factory
	function alertFactory(title,type,hasButton,cssClass,clickFn) {
		
		//firstly remove the alert modal
		$("#alert-modal") ? $("#alert-modal").remove() : 1;
		if (typeof(hasButton) == "undefined" || null == hasButton) hasButton = true;
		if (!cssClass)
			cssClass = "alert-width-3";
		var icon = "alertIcon";
		var buttonHtml = hasButton ? "<button class='btn btn-primary confirm' data-dismiss='modal' type='button'>确定</button>" :"";
		
		switch (type) {
		case "normal" :
			break;
		case "warn" :
			icon = "warnIcon";
			break;
		case "error" :
			icon = "errorIcon";
			break;
		case "confirm" : 
			icon = "confirmIcon";
			cssClass = "alert-width-4";
			buttonHtml = "<button class='btn btn-default selectCancel' type='button' data-dismiss='modal'>取消</button>" + 
			"<button class='btn btn-primary selectConfirm' type='button' data-dismiss='modal'>确定</button>";
			break;
		default :
			icon = "alertIcon";
		}
		var alertDiv = "<div id='alert-modal' role='dialog' class='modal fade in' style='display:block;' tabindex='-1' aria-labelledby='cf-alert-modal'></div>";
		$("body").append(alertDiv);
		$("#alert-modal").append(basicDialog);
		$("#alert-modal").find(".modal-footer").remove();
		//initial UI
		$("#alert-modal").find(".modal-dialog").addClass(cssClass);
		var bodyContent = "<div id='icons'>" +
								"<div class='"+icon+"'></div>" +
								"<div class='tip'>"+title+"</div>" +
							"</div>";
		
		$("#alert-modal").find(".modal-body").append(bodyContent);
		$("#alert-modal").find(".modal-header h4").text("提示");
		if (hasButton) {
			$("#alert-modal").find("#icons").append("<div id='alertBtn'>"+buttonHtml+"</div>");
		}
		
		//place the icon on vertical middle of the text DIV
		var iconDiv = $("."+icon);
		var tipDiv = $("#icons>div.tip");
	
		//base on the modal width ajust the tip text
		var body = $("#alert-modal").find(".modal-body");
		var bodyWidth = body.width();
		var bodyMargin = body.css("margin-left");
		var iconContentWidth = iconDiv.width();
		var iconMargin = iconDiv.css("margin-left");
		var textWidth = bodyWidth - 2 * parseInt(bodyMargin) - parseInt(iconMargin) - parseInt(iconContentWidth) - parseInt(tipDiv.css("margin-left"));
		tipDiv.css("width",textWidth);
		
		var textDivHeight = tipDiv.height();
		var selfHeight = iconDiv.height();
		
		if (textDivHeight > selfHeight) {
			$("."+icon).css({
				position : "relative",
				bottom : (textDivHeight - selfHeight) / 2 + "px"
	 		});
		}
		if (clickFn) {
			$("#alertBtn>.confirm").removeAttr("data-dismiss");
			$("#alertBtn>.confirm").on("click",function(e){
				clickFn();
				$(this).parents("div[id=alert-modal]").next("div[class*=modal-backdrop]").remove();
				$(this).parents("div[id=alert-modal]").remove();
			});
		}
		
		$("#alert-modal").find(".modal-header>.close").on("click",function(e) {
			//取消按钮不自动关闭
			$("#alert-modal").modal("hide");
		});
	}
	
	//listen the confrim dialog event
	function confirmListener(yesFn,noFn) {

		//confirm callback function
		$("#alertBtn>.selectConfirm").on("click",function(e){
			try {
				//if pass the confirm function ,execute it
				$(this).parents("div[id=alert-modal]").next("div[class*=modal-backdrop]").remove();
				if (yesFn)
					yesFn();
				if (!yesFn)
					$.confrimCallback();
			}catch (e) {
				console.log(e);
			}
		});
		
		//cancel callback function
		$("#alertBtn>.selectCancel").on("click",function(e){

			try {
				//if pass the confirm function ,execute it
				if (noFn)
					noFn();
				if (!noFn)
					$.cancelCallback();
			}catch (e) {
				console.log(e);
			}
		});
	}
	
	//common alert modal
	$.alert = function(title,hasButton,cssClass,clickFn) {
		alertFactory(title,"normal",hasButton,cssClass,clickFn);
		$("#alert-modal").modal({
			show:true,
			backdrop:"static"
		});
	};
	
	//error alert modal
	$.errorAlert = function(title,hasButton,cssClass,clickFn) {
		alertFactory(title,"error",hasButton,cssClass,clickFn);
		$("#alert-modal").modal({
			show:true,
			backdrop:"static"
		});
	};
	
	//warn alert modal
	$.warmAlert = function(title,hasButton,cssClass,clickFn) {
		alertFactory(title,"warn",hasButton,cssClass,clickFn);
		$("#alert-modal").modal({
			show:true,
			backdrop:"static"
		});
	};
	
	//confirm alert modal
	$.confirmAlert = function(title,yesFn,noFn,hasButton,cssClass) {
	
		alertFactory(title,"confirm",hasButton,cssClass);
		$("#alert-modal").modal({
			show:true,
			backdrop:"static"
		});
		confirmListener(yesFn,noFn);
	};
	
})(jQuery);